
package com.jf.cloud.search.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.dto.EsPageDTO;
import com.jf.cloud.api.product.feign.CategoryShopFeignClient;
import com.jf.cloud.api.product.feign.SkuFeignClient;
import com.jf.cloud.api.product.feign.SpuFeignClient;
import com.jf.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.constant.StatusEnum;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.i18n.I18nMessage;
import com.jf.cloud.common.i18n.LanguageEnum;
import com.jf.cloud.common.product.bo.EsBrandBO;
import com.jf.cloud.common.product.constant.SpuType;
import com.jf.cloud.common.product.constant.SupplierDeliveryType;
import com.jf.cloud.common.product.constant.SupplierSpuType;
import com.jf.cloud.common.product.dto.ProductSearchDTO;
import com.jf.cloud.common.product.vo.SkuVO;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.product.vo.search.ProductSearchVO;
import com.jf.cloud.common.product.vo.search.SpuAdminVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.search.constant.DataType;
import com.jf.cloud.search.constant.EsConstant;
import com.jf.cloud.search.constant.EsRenovationProductSortEnum;
import com.jf.cloud.search.manager.ProductSearchManager;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.compress.utils.Lists;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品搜索
 *
 * @author zz
 * @date 2020/11/16
 */
@RestController("adminSearchSpuController")
@RequestMapping("/mp/search")
@Tag(name = "admin-spu管理列表接口")
public class ProductSearchController {

    @Autowired
    private ProductSearchManager productSearchManager;
    @Autowired
    private SkuFeignClient skuFeignClient;
    @Autowired
    private CategoryShopFeignClient categoryShopFeignClient;
    @Autowired
    private SpuFeignClient spuFeignClient;
    @Autowired
    private SupplierDetailFeignClient supplierDetailFeignClient;

    @GetMapping("/page")
    @Operation(summary = "商品信息列表" , description = "商品信息列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> page(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        productSearchDTO.setFetchSource(EsConstant.SHOP_FETCH_SOURCE);
        productSearchDTO.setShopId(shopId);
        if (Objects.nonNull(productSearchDTO.getSupplierDeliveryType())) {
            productSearchDTO.setSpuMold(0);
        }
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        List<SpuAdminVO> spuList = searchPage.getList();
        List<Long> spuIds = spuList.stream().map(e -> e.getSpuId()).collect(Collectors.toList());
        List<Long> supplierSpuIds = Lists.newArrayList();
        if(CollUtil.isNotEmpty(spuList)){
            for(SpuAdminVO item :spuList){
                if(Objects.equals(item.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value()) && Objects.nonNull(item.getSupplierSpuId())){
                    supplierSpuIds.add(item.getSupplierSpuId());
                }
            }
        }
        if(CollUtil.isNotEmpty(supplierSpuIds)){
            //代销商品 供应商商品更新后代销商品是否已同步更新 值
            List<SpuVO> spuIsSyn = spuFeignClient.getSpuIsSynUpdate(spuIds).getData();
            Map<Long, Integer> isSynUpdate = spuIsSyn.stream().collect(Collectors.toMap(SpuVO::getSpuId, SpuVO::getIsSynUpdate));
            Map<Long, Integer> stockInfo = spuIsSyn.stream().collect(Collectors.toMap(SpuVO::getSpuId, SpuVO::getTotalStock));
            for (SpuAdminVO spuAdminVO : searchPage.getList()) {
                spuAdminVO.setIsSynUpdate(isSynUpdate.get(spuAdminVO.getSpuId()));
                //代销商品  供应商发货时，显示供应商库存
                if (Objects.equals(spuAdminVO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())){
                    spuAdminVO.setStock(stockInfo.get(spuAdminVO.getSpuId()));
                }
            }
        }
        //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
        List<SpuAdminVO> data = spuFeignClient.checkCommissionSpuIsUpdateMsg(spuList).getData();
        searchPage.setList(data);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/page_distribution_spu")
    @Operation(summary = "分销商品列表" , description = "分销商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> pageDistributionSpu(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            productSearchDTO.setShopId(shopId);
        }
        productSearchDTO.setFetchSource(EsConstant.DISTRIBUTION_SPU_SOURCE);
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/page_supply_spu")
    @Operation(summary = "商家搜索供应商品列表" , description = "商家搜索供应商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> pageSupplySup(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        Integer sysType = AuthUserContext.get().getSysType();
        ServerResponseEntity<List<Long>> oneCategoryIdByShopId = categoryShopFeignClient.getOneCategoryIdByShopId(shopId, sysType, I18nMessage.getLang());
        if (Objects.isNull(oneCategoryIdByShopId.getData())) {
            return ServerResponseEntity.success();
        }
        // 查询出一已经代销的商品
        ProductSearchDTO productSearchDTO1 = new ProductSearchDTO();
        productSearchDTO1.setSupplierSpuType(SupplierSpuType.CONSIGNMENT.value());
        productSearchDTO1.setShopId(shopId);
        productSearchDTO1.setFetchSource(EsConstant.CONSIGNMENT_SPU);
        productSearchDTO1.setShopQuerySupplierSpu(true);
        EsPageVO<SpuAdminVO> spuAdminEsPage = productSearchManager.adminPage(pageDTO, productSearchDTO1);
        List<Long> spuIdList = spuAdminEsPage.getList().stream().map(SpuAdminVO::getSupplierSpuId).collect(Collectors.toList());
        //根据分类查找对应的供应商id
        ServerResponseEntity<List<Long>> supplyIdByCategoryIds = categoryShopFeignClient.getSupplyIdByCategoryIds(oneCategoryIdByShopId.getData());
        //es搜索商品
        productSearchDTO.setSupplierIds(supplyIdByCategoryIds.getData());
        productSearchDTO.setCategoryIds(oneCategoryIdByShopId.getData());
        productSearchDTO.setFetchSource(EsConstant.SUPPLIER_SPU);
        productSearchDTO.setSupplierSpuType(1);
        productSearchDTO.setShopQuerySupplierSpu(true);
        EsPageVO<SpuAdminVO> spuAdminPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        List<SpuAdminVO> list = spuAdminPage.getList();
        // 需要过滤的商品id(过滤掉没有导入，且供应商商品状态不是上架状态的商品)
        List<Long> filterSpuIdList = new ArrayList<>();
        for (SpuAdminVO spuAdminVO : list) {
            boolean contains = spuIdList.contains(spuAdminVO.getSpuId());
            if (!contains){
                if (!Objects.equals(spuAdminVO.getSpuStatus(), StatusEnum.ENABLE.value())){
                    filterSpuIdList.add(spuAdminVO.getSpuId());
                }
            }
        }
        productSearchDTO.setSpuIdsExclude(filterSpuIdList);
        spuAdminPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        list = spuAdminPage.getList();
        ServerResponseEntity<List<SupplierApiDetailVO>> supplierResp = supplierDetailFeignClient.listSupplierDetailBySupplierIds(supplyIdByCategoryIds.getData());
        Map<Long, String> supplierNameMap = supplierResp.getData().stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, SupplierApiDetailVO::getSupplierName));
        for (SpuAdminVO spuAdminVO : list) {
            spuAdminVO.setSupplyPriceFee(spuAdminVO.getPriceFee());
            //品牌名称
            setBrandName(spuAdminVO);
            spuAdminVO.setSupplierName(supplierNameMap.get(spuAdminVO.getSupplierId()) == null ? spuAdminVO.getShopName() : supplierNameMap.get(spuAdminVO.getSupplierId()));
        }
        //验证是否代销了供应商商品
        ServerResponseEntity<List<SpuAdminVO>> result = spuFeignClient.isCommissionByShopIdAndSpuId(list, shopId);
        spuAdminPage.setList(result.getData());
        return ServerResponseEntity.success(spuAdminPage);
    }

    @GetMapping("/page_supplier_spu_list")
    @Operation(summary = "获取某个供应商或商家（不含代销商品）的商品列表" , description = "获取某个供应商或商家（不含代销商品）的商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> pageSupplierSpuList(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        if (Objects.isNull(productSearchDTO.getCategoryId()) || Objects.isNull(productSearchDTO.getSupplierIds())) {
            ServerResponseEntity<List<Long>> categoryIdsResp = categoryShopFeignClient.getCategoryIdsByShopId(shopId, SysTypeEnum.MULTISHOP.value());
            if (!categoryIdsResp.isSuccess()) {
                throw new LuckException(categoryIdsResp.getMsg());
            }
            // 根据分类过滤商品
            if (Objects.isNull(productSearchDTO.getCategoryId())) {
                productSearchDTO.setCategoryIds(categoryIdsResp.getData());
            }
            // 根据供应商过滤商品
            if(CollUtil.isEmpty(productSearchDTO.getSupplierIds())) {
                //根据分类查找对应的供应商id
                ServerResponseEntity<List<Long>> supplyIdByCategoryIds = categoryShopFeignClient.getSupplyIdByCategoryIds(categoryIdsResp.getData());
                //es搜索商品
                productSearchDTO.setSupplierIds(supplyIdByCategoryIds.getData());
            }
        }
        productSearchDTO.setFetchSource(EsConstant.CONSIGNMENT_SPU);
        productSearchDTO.setHasStock(1);
        productSearchDTO.setSpuStatus(StatusEnum.ENABLE.value());
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        if (CollectionUtil.isEmpty(searchPage.getList())) {
            return ServerResponseEntity.success(searchPage);
        }
        List<Long> spuIds = searchPage.getList().stream().map(SpuAdminVO::getSpuId).collect(Collectors.toList());
        // 商家端查询供应商库存时，stock为商家库存，supplierStock为供应商库存
        List<SkuVO> skuListResp;
        boolean isQueryShopStock = productSearchDTO.getShopQuerySupplierSpu() != null && productSearchDTO.getShopQuerySupplierSpu();
        if (isQueryShopStock) {
            skuListResp = skuFeignClient.listSupplierBySpuIds(spuIds, shopId).getData();
        } else {
            skuListResp = skuFeignClient.listBySpuIds(spuIds).getData();
        }
        Map<Long, List<SkuVO>> skuMap = skuListResp.stream().collect(Collectors.groupingBy(SkuVO::getSpuId));
        // 去掉库存为0的sku
        for (SpuAdminVO spuAdminVO : searchPage.getList()) {
            spuAdminVO.setSkuList(skuMap.get(spuAdminVO.getSpuId()));
            List<SkuVO> skuList = skuMap.get(spuAdminVO.getSpuId());
            skuList.removeIf(skuVO -> (isQueryShopStock && skuVO.getSupplierStock() == 0)
                    || (!isQueryShopStock && Objects.equals(skuVO.getStock(), 0)));
            spuAdminVO.setSkuList(skuList);
        }
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/page_shop_spu_list")
    @Operation(summary = "获取商家的商品列表" , description = "获取商家的商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> pageShopSpuList(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        ServerResponseEntity<List<Long>> categoryIdsResp = categoryShopFeignClient.getCategoryIdsByShopId(shopId, SysTypeEnum.MULTISHOP.value());
        if (!categoryIdsResp.isSuccess()) {
            throw new LuckException(categoryIdsResp.getMsg());
        }
        productSearchDTO.setCategoryIds(categoryIdsResp.getData());
        productSearchDTO.setShopId(shopId);
        productSearchDTO.setFetchSource(EsConstant.SHOP_FETCH_SOURCE);
        productSearchDTO.setDataType(DataType.ALL_PROD.value());
        productSearchDTO.setSupplierSpuType(null);
        productSearchDTO.setAppDisplay(true);

        productSearchDTO.setSpuStatus(StatusEnum.ENABLE.value());
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        if (CollectionUtil.isEmpty(searchPage.getList())) {
            return ServerResponseEntity.success(searchPage);
        }
        List<Long> spuIds = searchPage.getList().stream().map(SpuAdminVO::getSpuId).collect(Collectors.toList());
        List<SkuVO> skuListResp = skuFeignClient.listBySpuIds(spuIds).getData();
        Map<Long, List<SkuVO>> skuMap = skuListResp.stream().collect(Collectors.groupingBy(SkuVO::getSpuId));
        for (SpuAdminVO spuAdminVO : searchPage.getList()) {
            spuAdminVO.setSkuList(skuMap.get(spuAdminVO.getSpuId()));
        }
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/pageConsignmentSpu")
    @Operation(summary = "代销商品列表" , description = "代销商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> pageConsignmentSpu(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        productSearchDTO.setSupplierSpuType(SupplierSpuType.CONSIGNMENT.value());
        productSearchDTO.setShopId(shopId);
        productSearchDTO.setFetchSource(EsConstant.CONSIGNMENT_SPU);
        productSearchDTO.setShopQuerySupplierSpu(false);
        EsPageVO<SpuAdminVO> spuAdminEsPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        if (spuAdminEsPage.getList().size() == 0) {
            //查询为空直接返回
            return ServerResponseEntity.success(spuAdminEsPage);
        } else {
            List<SpuAdminVO> commissionSpu = spuAdminEsPage.getList();
            //供商品id
            List<Long> supplierSpuIds = commissionSpu.stream().map(e -> e.getSupplierSpuId()).collect(Collectors.toList());
            //代销商品id
            List<Long> spuIds = commissionSpu.stream().map(e -> e.getSpuId()).collect(Collectors.toList());
            //供应商品信息
            ServerResponseEntity<List<SpuVO>> supplierEntity = spuFeignClient.listSpuBySpuIds(supplierSpuIds);
            //代销商品 供应商商品更新后代销商品是否已同步更新 值
            List<SpuVO> supplierSpu = supplierEntity.getData();
            List<SpuVO> spuIsSyn = spuFeignClient.getSpuIsSynUpdate(spuIds).getData();
            Map<Long, Integer> isSynUpdate = spuIsSyn.stream().collect(Collectors.toMap(SpuVO::getSpuId, SpuVO::getIsSynUpdate));
            //供应商品供货价
            Map<Long, Long> supplierSpuFee = supplierSpu.stream().collect(Collectors.toMap(SpuVO::getSpuId, SpuVO::getPriceFee));
            for (SpuAdminVO spuAdminVO : commissionSpu) {
                spuAdminVO.setIsSynUpdate(isSynUpdate.get(spuAdminVO.getSpuId()));
                //品牌名称
                setBrandName(spuAdminVO);
                //设置供货价
                spuAdminVO.setSupplyPriceFee(supplierSpuFee.get(spuAdminVO.getSupplierSpuId()));
            }

            //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
            List<SpuAdminVO> result = spuFeignClient.checkCommissionSpuIsUpdateMsg(commissionSpu).getData();
            spuAdminEsPage.setList(result);
            return ServerResponseEntity.success(spuAdminEsPage);
        }
    }

    public void setBrandName(SpuAdminVO spuAdminVO) {
        //品牌名称
        Integer lang = I18nMessage.getLang();
        EsBrandBO brand = spuAdminVO.getBrand();
        if (!Objects.isNull(brand)) {
            if (Objects.equals(lang, LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                spuAdminVO.setBrandName(brand.getBrandNameZh());
            }
            if (Objects.equals(lang, LanguageEnum.LANGUAGE_EN.getLang())) {
                spuAdminVO.setBrandName(brand.getBrandNameEn());
            }
        }
    }


    @GetMapping("/pageComboAddSpu")
    @Operation(summary = "套餐以及赠品选择商品列表" , description = "套餐以及赠品选择商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> pageComboAddSpu(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO){
        Long shopId = AuthUserContext.get().getTenantId();
        productSearchDTO.setFetchSource(EsConstant.SHOP_FETCH_SOURCE);
        productSearchDTO.setShopId(shopId);
        productSearchDTO.setSpuType(SpuType.NORMAL.value());
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        List<SpuAdminVO> spuList = searchPage.getList();
        //获取sku
        List<SpuAdminVO> spuAdminList = skuFeignClient.setSpuSku(spuList).getData();
        searchPage.setList(spuAdminList);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/renovation_page")
    @Operation(summary = "商品信息列表(商家装修商品列表)" , description = "商品信息列表(商家装修商品列表)")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> renovationPage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        productSearchDTO.setShopId(AuthUserContext.get().getTenantId());
        Long size = null;
        if(Objects.equals(productSearchDTO.getShowSpuType(),1)){
            if(Objects.equals(productSearchDTO.getEsRenovationSpuSort(), EsRenovationProductSortEnum.CREATE_TIME_ASC.value()) || Objects.equals(productSearchDTO.getEsRenovationSpuSort(),EsRenovationProductSortEnum.CREATE_TIME_DESC.value())){
                productSearchDTO.setSort(productSearchDTO.getEsRenovationSpuSort());
            }else {
                // 获取指定规则的商品ids
                size = getSpuIds(pageDTO, productSearchDTO);
            }
        }
        EsPageVO<ProductSearchVO> searchPage =  productSearchManager.renovationPage(pageDTO, productSearchDTO,size);
        productSearchManager.loadData(productSearchDTO, searchPage.getList());
        return ServerResponseEntity.success(searchPage);
    }

    private Long getSpuIds(EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        Long shopId = Objects.isNull(productSearchDTO.getShopId()) ? 0L :  productSearchDTO.getShopId();
        String key = EsConstant.RENOVATION_PRODUCT_IDS_CACHE + CacheNames.UNION + shopId +
                CacheNames.UNION_KEY + productSearchDTO.getEsTimeRange() + CacheNames.UNION_KEY + productSearchDTO.getEsRenovationSpuSort()
                + CacheNames.UNION_KEY + productSearchDTO.getPrimaryCategoryId();
        if(!RedisUtil.hasKey(key)){
            productSearchManager.addRenovationSpuCache(key,productSearchDTO, shopId, EsConstant.RENOVATION_PRODUCT_IDS_CACHE_TIME);
//            return new ArrayList<>();
        }
        Long size = RedisUtil.getListSize(key);
        long startNum = (long) (pageDTO.getPageNum() - 1) * pageDTO.getPageSize();
        long endNum = (long) pageDTO.getPageNum() * pageDTO.getPageSize() - 1;
        endNum = Math.min(endNum,size - 1);
        List spuIds = RedisUtil.getListRange(key, startNum, endNum);
        productSearchDTO.setSpuIds(spuIds);
        return size;
    }
}
